//
//  BaseHomeVC.swift
//  ZYA
//
//  Created by 邱仙凯 on 2024/12/23.
//  Copyright © 2024 zwb. All rights reserved.
//

import UIKit
import JJCollectionViewRoundFlowLayout_Swift

class BaseHomeVC: UIViewController, ModifyPasswordable {
    
    let InitPWD_KEY = "USE_InitPWD_KEY"
    
    var modifyPwdSuccessBlock: (() -> Void)?
    
    // MARK: -  生命周期
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        BadgeUtil.shared.getBadge({ _ in
            self.collectionView.reloadData()
        })
        // 提示修改初始密码
        if UserDefaults.standard.bool(forKey: "ANOASTORE_UseInitialPassword") {
            if !UserDefaults.standard.bool(forKey: InitPWD_KEY) {
                UserDefaults.standard.set(true, forKey: InitPWD_KEY)
                UserDefaults.standard.synchronize()
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
                    KSToast("您还在使用初始密码，请修改")
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2) {
                        self.go2ModifyPassword(force: true) { [weak self] in
                            self?.modifyPwdSuccessBlock?()
                        }
                        
                        UserDefaults.standard.set(false, forKey: self.InitPWD_KEY)
                        UserDefaults.standard.synchronize()
                    }
                }
            }
        } else {
            // 避免有的项目没有使用 UserDefaults
            if UseInitialPassword {
                if !UserDefaults.standard.bool(forKey: InitPWD_KEY) {
                    UserDefaults.standard.set(true, forKey: InitPWD_KEY)
                    UserDefaults.standard.synchronize()
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
                        KSToast("您还在使用初始密码，请修改")
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2) {
                            self.go2ModifyPassword(force: true) { [weak self] in
                                self?.modifyPwdSuccessBlock?()
                            }
                            
                            UserDefaults.standard.set(false, forKey: self.InitPWD_KEY)
                            UserDefaults.standard.synchronize()
                        }
                    }
                }
            }
        }
        
        
        navView.iconButton.kf.setImage(with: URL(string: USERINFO.headerUrl.unwrap), for: .normal, options: [.forceRefresh])
        
        navigationController?.setNavigationBarHidden(true, animated: false)

    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        navigationController?.setNavigationBarHidden(false, animated: false)
    }
    
    var wsyArr = [QuotesModel]()
    var nsyArr = [QuotesModel]()
    var tzzArr = [QuotesModel]()
    var hangqingArr = [QuotesModel]()

     
    var changyongArr:[String] = []
    var daibanGroup1:[String] = []

    var expectChangyong = [MenuItem]()
    var expectDaiban = [[MenuItem]]()
    var menuGroupArrNew = [(String,String)]()
    var navView:ZyaHomeNavView!
    var itemMargin:CGFloat = 8
    var dingNavHeight:CGFloat = 35
    var homeBgImg:UIImageView = {
        var v = UIImageView()
        v.image = UIImage(named: "home_bg")
        return v
    }()
    lazy var collectionView:UICollectionView = {
        // 1.创建layout
        
        let layout = JJCollectionViewRoundFlowLayout_Swift()
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 0
//        layout.sectionInset = UIEdgeInsets(top: 6, left: 24, bottom: 30, right: 24)
        
        // 2.创建UICollectionView
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height), collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false

       
        collectionView.register(HomeHangqingCell.self, forCellWithReuseIdentifier: HomeHangqingCell.identifier)

        collectionView.register(HomeDaibanCell.self, forCellWithReuseIdentifier: HomeDaibanCell.identifier)
        collectionView.register(HomeChangyongCell.self, forCellWithReuseIdentifier: HomeChangyongCell.identifier)

        
        collectionView.register(SpaceHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: SpaceHeader.identifier)
        
        return collectionView
    }()
    
    // 子类实现
    func getDaibanGroup() -> [String] {
        return []
    }
    
    func getChangyong() -> [String] {
        return []
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        daibanGroup1 = getDaibanGroup()
        changyongArr = getChangyong()
        menuGroupArrNew = [("常用菜单","x"),
                           ("我的待办","wddb_hh"),
                           ("市场行情","schq_hh")]
        self.view.backgroundColor = UIColor(kshex: "#EFF4FA")
        self.view.addSubview(homeBgImg)
        homeBgImg.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(246)
        }
        initSearchController()
        setMenu()
        if isBaiduMapPlatform() {
            bMapHelper.shared.initMap()
        } else {
            GaoDeHelper.shared.initGaoDe()
        }

        collectionView.contentInset = UIEdgeInsets(top: dingNavHeight + 10, left: 0, bottom: 10, right: 0)
         
        collectionView.delegate = self
        collectionView.dataSource = self
        self.view.addSubview(collectionView)
    }
    
    // 配置菜单
    func setMenu() {
        expectChangyong = changyongArr.compactMap { one -> MenuItem? in
            let mArr = MenuPool.filter{ $0.desc.unwrap == one}
            return mArr.first
        }  
    
            // 获取菜单， 处理权限，
        let dealOnx =   menuArrDealed(daibanGroup1)
        
        var ddArr = [MenuItem]()
            // 分成6个一组
        for i in 0..<dealOnx.count {
            ddArr.append(dealOnx[i])
            if ddArr.count == 6 {
                expectDaiban.append(ddArr)
                ddArr.removeAll()
            }
        }
        // 有剩，再加上
        if ddArr.count > 0 {
            expectDaiban.append(ddArr)
        }
        
        
        self.collectionView.reloadData()
    }
    
    func initSearchController() {
        navView = ZyaHomeNavView(frame:CGRect(x:0,y:-dingNavHeight,width:KSGlobal.screenW,height:dingNavHeight))
        navView.iconButton.addTouchUpInSideAction { _ in
            let vc = NewPersonVC()
            vc.cv.searchButton.isHidden = true
            self.navigationController?.pushViewController(vc,animated: true)
        }
        navView.saoButton.addTouchUpInSideAction { _ in
            KSToast("扫码升级中")
        }
        navView.searchButton.addTouchUpInSideAction { _ in
            KSToast("搜索升级中")
        }
        navView.setButton.addTouchUpInSideAction { _ in
            
            let  vc = AWSettingVC()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
         
        let toolbar = UIToolbar()
        toolbar.barStyle = UIBarStyle.default
        toolbar.sizeToFit()
        let buttonflexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
        let buttonDone = UIBarButtonItem(title: "完成", style: UIBarButtonItem.Style.done, target: self, action: #selector(doneClickss))
        buttonDone.tintColor = UIColor.black
        toolbar.setItems([buttonflexible, buttonDone], animated: true)
        
        navView.searchBar!.inputAccessoryView = toolbar
        
    
        navView.searchBar!.delegate = self
        
        
        self.collectionView.addSubview(navView)
        getmarket()
    }
    
    func getmarket() {
        KSNetworkOK.shared.doRequest(ZHUOKAPI.getMarketSituationByDays(z_days: "7")) { (data:BaseResult<QuotesModel>) in
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    
                    self.wsyArr = infos.filter{$0.zTypeId.unwrap == "1"}.sorted(by: {$0.zDate.unwrap < $1.zDate.unwrap})
                    self.nsyArr = infos.filter{$0.zTypeId.unwrap == "2"}.sorted(by: {$0.zDate.unwrap < $1.zDate.unwrap})
                    self.tzzArr = infos.filter{$0.zTypeId.unwrap == "3"}.sorted(by: {$0.zDate.unwrap < $1.zDate.unwrap})

                    
                    
                    
                    self.hangqingArr = infos.filter{$0.zDate.unwrap == Date.today}
                    
                    if checkPlatform(type: .zhuYouAn) {
                        // 如果没有今天的,往前取,最多往前 3 天
                        if self.hangqingArr.count == 0 {
                            self.hangqingArr = infos.filter{$0.zDate.unwrap == Date.todayPres(1)}
                        }
                        if self.hangqingArr.count == 0 {
                            self.hangqingArr = infos.filter{$0.zDate.unwrap == Date.todayPres(2)}
                        }
                        if self.hangqingArr.count == 0 {
                            self.hangqingArr = infos.filter{$0.zDate.unwrap == Date.todayPres(3)}
                        }
                    }
                    self.collectionView.reloadData()
                }
            }
        }
    }
}

extension BaseHomeVC : JJCollectionViewDelegateRoundFlowLayout_Swift{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, borderEdgeInsertsForSectionAtIndex section: Int) -> UIEdgeInsets {
        
        switch menuGroupArrNew[section].0 {
        case "常用菜单":
            return UIEdgeInsets.init(top: 0, left: newModuleLeading, bottom: 0, right: newModuleLeading)
        case "我的待办":
          return UIEdgeInsets.init(top: -8, left: newModuleLeading, bottom: 10, right: newModuleLeading)
        default:
            return UIEdgeInsets.init(top: -8, left: newModuleLeading, bottom: 15, right: newModuleLeading)
            
        }
       
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, configModelForSectionAtIndex section: Int) -> JJCollectionViewRoundConfigModel_Swift {
        
        switch menuGroupArrNew[section].0 {
        case "常用菜单":
            let model = JJCollectionViewRoundConfigModel_Swift.init()
            model.backgroundColor = .clear
            return model
        case "功能模块":
            let model = JJCollectionViewRoundConfigModel_Swift.init()
            return model
       
        default:
            let model = JJCollectionViewRoundConfigModel_Swift.init()
            model.cornerRadius = 8
            model.backgroundColor = UIColor.white
            return model
   
            
        }
         
    }
}


// MARK: -   代理和数据源
extension BaseHomeVC:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: SpaceHeader.identifier, for: indexPath) as! SpaceHeader
        
        switch menuGroupArrNew[indexPath.section].0 {
        case "常用菜单":
             header.bg.isHidden = true
            header.titleLabel.isHidden = true
            header.img.isHidden = true
            header.tipIcon.isHidden = true

        case "我的待办":
             header.bg.isHidden = false
            header.titleLabel.isHidden = false
            header.img.isHidden = false
            header.tipIcon.isHidden = true

            header.titleLabel.text = menuGroupArrNew[indexPath.section].0
            header.img.image = UIImage(named: menuGroupArrNew[indexPath.section].1)
            header.jianbianBg.setGradient(type: .left2right, startColor: UIColor(kshex: "fff3f3"), endColor: .white)
        default:
            // 市场行情
            header.bg.isHidden = false
           header.titleLabel.isHidden = false
           header.img.isHidden = false
            
            var tipStr = ""
            let tipArr = self.hangqingArr.filter{$0.zDataSource.unwrap != ""}
            if tipArr.count > 0 {
                tipStr = tipArr.first!.zDataSource.unwrap
            }
            if tipStr != "" {
                header.tipIcon.isHidden = false
                header.tipIcon.addTouchUpInSideAction { _ in
                    alertUtil(title: tipStr, withCancel: false,operateS: [nameAction(name: "确定", action: { _ in
                        
                    })])
                }
            } else {
                header.tipIcon.isHidden = true

            }
 
            
        

           header.titleLabel.text = menuGroupArrNew[indexPath.section].0
           header.img.image = UIImage(named: menuGroupArrNew[indexPath.section].1)
           header.jianbianBg.setGradient(type: .left2right, startColor: UIColor(kshex: "fff8f3"), endColor: .white)
        }
       

        return header
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        switch menuGroupArrNew[section].0 {
        case "常用菜单":
            return CGSize(width: KSGlobal.screenW, height: 12)
        default:
            
            return CGSize(width: KSGlobal.screenW, height: KSGlobal.screenH * 0.05)
        }
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return menuGroupArrNew.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch menuGroupArrNew[section].0 {
        case "常用菜单":
            return expectChangyong.count
        case "我的待办":
            return 1
   
        case "市场行情":
            return 1
        default:
            return 0
            
        }
       
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        switch menuGroupArrNew[indexPath.section].0 {
        case "常用菜单":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeChangyongCell.identifier, for: indexPath as IndexPath) as! HomeChangyongCell
           
              
            cell.img.image = UIImage(named:"\(expectChangyong[indexPath.row].imgStr.unwrap)")
                
            cell.title.text = expectChangyong[indexPath.row].title
   
          
            return cell
        case "我的待办":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeDaibanCell.identifier, for: indexPath as IndexPath) as! HomeDaibanCell
           
            cell.dataGroup = expectDaiban
            cell.ddclo = { item in
                let oneAc = item.enterFunc
                oneAc!(self)
            }
 
            return cell
     // 市场行情
        default:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeHangqingCell.identifier, for: indexPath as IndexPath) as! HomeHangqingCell
            
            cell.showQuotesData(self.hangqingArr)
            cell.wsyArr = self.wsyArr
            cell.nsyArr = self.nsyArr
            cell.tzzArr = self.tzzArr
            cell.collectionView.reloadData()
            return cell
 
            
        }
        
    
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
                
        switch menuGroupArrNew[indexPath.section].0 {
       
        case "常用菜单":
        
            let oneAc = expectChangyong[indexPath.row].enterFunc
            oneAc!(self)
  
        default:
            break
 
        }
    }
    
    
    // 设置itemsize
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let sectionW = self.view.ks_width - newModuleLeading * 2
  
        switch menuGroupArrNew[indexPath.section].0 {
        case "常用菜单":
            let c_width = floor(sectionW/4) - 9
            return CGSize(width: c_width, height: KSGlobal.screenH * 0.086)
        case "我的待办":
            let c_width = sectionW
            return CGSize(width: c_width, height: KSGlobal.screenH * 0.17)
            // 市场行情
        default:
            let c_width = sectionW
            return CGSize(width: c_width, height: KSGlobal.screenH * 0.29)
            
        }
    }
 
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        switch menuGroupArrNew[section].0 {
        case "常用菜单":
            return UIEdgeInsets(top: 6, left: 7, bottom: 12, right: 7)
        case "我的待办":
            return UIEdgeInsets(top: 15, left: newModuleLeading + itemMargin, bottom: 30, right: newModuleLeading + itemMargin)
            // 市场行情
          default:
            return UIEdgeInsets(top: 15, left: newModuleLeading + itemMargin, bottom: 30, right: newModuleLeading + itemMargin)
            
        }
    }
}

extension BaseHomeVC: UISearchBarDelegate {
    @objc func doneClickss() {
        self.navView.searchBar!.resignFirstResponder()
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//        keyWord = searchText
//        self.dealTempList()
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
      
    }
}
